package com.guawazi.fragment;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;

import com.guawazi.MainActivity;
import com.guawazi.R;
import com.guawazi.adapter.ScrollablePanelAdapter;
import com.guawazi.base.BaseFragment;
import com.guawazi.bean.DataEntity;
import com.guawazi.nohttp.HttpListener;
import com.guawazi.utils.JsonUtil;
import com.guawazi.utils.SharedPreferenceUtils;
import com.guawazi.widget.scrollablepanel.ScrollablePanel;
import com.orhanobut.logger.Logger;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class TableFragment extends BaseFragment {
    @BindView(R.id.scrollable_panel)
    ScrollablePanel scrollablePanel;
    Unbinder unbinder;

    //handler
    private static final int UPDATE_VIEW = 0x01;
    //http
    private static final int REQUIRE_DATA = 0x01;

    private MainActivity activity;
    private ScrollablePanelAdapter scrollablePanelAdapter;
    private List<DataEntity> dataList = new ArrayList<>();
    private List<String> attrList = new ArrayList<>();
    private Calendar startcal;
    private int mYear, mMonth, mDay;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UPDATE_VIEW:
                    scrollablePanelAdapter = new ScrollablePanelAdapter(getActivity());
                    generateData(scrollablePanelAdapter);
                    scrollablePanel.setPanelAdapter(scrollablePanelAdapter);
                    break;
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        activity = (MainActivity) getActivity();
        initAttr();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_table_layout, container, false);
        unbinder = ButterKnife.bind(this, view);

//        //
//        dataList.clear();
//        for (int i = 0; i < 10; i++) {
//            DataEntity entity = new DataEntity();
//            entity.setId(i);
//            entity.setVoltageValue(i);
//            entity.setMarkerPosition("A");
//            entity.setAccelerationX(i);
//            entity.setAccelerationY(i);
//            entity.setAccelerationZ(i);
//            entity.setTime(i);
//            entity.setLongitude(i+"");
//            entity.setLatitude(i+"");
//            entity.setDate(12345);
//            entity.setJudgmentPosition("S");
//
//            dataList.add(entity);
//        }
//        handler.sendEmptyMessage(UPDATE_VIEW);
//        //

        startcal = Calendar.getInstance();
        mYear = startcal.get(Calendar.YEAR);
        mMonth = startcal.get(Calendar.MONTH);
        mDay = startcal.get(Calendar.DAY_OF_MONTH);

        activity.setMenuClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog datePickerDialog = new DatePickerDialog(activity, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {

                        DecimalFormat df = new DecimalFormat("00");
                        String strMonth = df.format(month + 1);
                        String strDay = df.format(dayOfMonth);
                        requestData(year + "-" + strMonth + "-" + strDay);
                    }
                }, mYear, mMonth, mDay);

                datePickerDialog.show();
            }
        });
        requestData();

        return view;
    }

    private void initAttr() {
        attrList.clear();
        attrList.add("脊背弯曲度");
        attrList.add("脊背状态");
        attrList.add("X轴");
        attrList.add("Y轴");
        attrList.add("Z轴");
        attrList.add("时间");
        attrList.add("纬度");
        attrList.add("经度");
        attrList.add("月日年");
        attrList.add("安全状态");
    }

    private void generateData(ScrollablePanelAdapter adapter) {
        adapter.setAttrInfoList(attrList);
        adapter.setDataInfoList(dataList);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public void setData(List<DataEntity> list) {
        dataList = list;
    }

    private void requestData() {
        requestData("");
    }

    private void requestData(String date) {
        Request<JSONObject> request = NoHttp.createJsonObjectRequest("http://119.23.48.248:3000/project/getAll", RequestMethod.GET);
        request.add("date", date);
        request.add("phoneNumber", SharedPreferenceUtils.getValue(activity, "phoneNum", ""));
        request.add("size", 100);
        activity.request(0x01, request, httpListener, false, true);
    }

    private HttpListener<JSONObject> httpListener = new HttpListener<JSONObject>() {

        @Override
        public void onSucceed(int what, Response<JSONObject> response) {
            if (response.getHeaders().getResponseCode() == 200) {
                switch (what) {
                    case 0x01: {
                        JSONObject object = response.get();
                        Logger.json(object.toString());
                        try {
                            int code = object.getInt("code");
                            if (code == 200) {
                                JSONObject object1 = object.getJSONObject("data");
                                JSONArray summary = object1.getJSONArray("summary");
                                dataList = JsonUtil.stringToList(summary.toString(), DataEntity.class);

                                handler.sendEmptyMessage(UPDATE_VIEW);
                            } else {
                                showToast(object.getString("msg"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                }
            }
        }

        @Override
        public void onFailed(int what, Response<JSONObject> response) {
            activity.showMessageDialog(R.string.request_failed, response.getException().getMessage());
        }
    };
}
